﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QFlow.Data;
using QFlow.Core;

namespace QFlow.Windows.Forms
{
    public partial class NewPurchaseOrderItem : Utils.BaseForm
    {
        bool _New, _Change = false, _ComboLoaded = false,_NonStockable;
        PurchaseOrder _pOrder;
        PurchaseItem _pItem;
        double _PurchaseUnitPrice, _SalesUnitPrice;

        /// <summary>
        /// Initializes a new instance of the <see cref="NewPurchaseOrderItem"/> class.
        /// </summary>
        /// <param name="sOrder">The s order.</param>
        /// <param name="context">The context.</param>
        public NewPurchaseOrderItem(PurchaseOrder order, QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
            _pOrder = order;
            _New = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NewPurchaseOrderItem"/> class.
        /// </summary>
        /// <param name="sOrder">The s order.</param>
        /// <param name="sItem">The s item.</param>
        /// <param name="context">The context.</param>
        public NewPurchaseOrderItem(PurchaseOrder pOrder, PurchaseItem pItem, QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
            _New = false;
            _pOrder = pOrder;
            _pItem = pItem;
            this.Text = QFlow.Windows.Properties.Resources.FRMEditPItem;
        }

        /// <summary>
        /// Handles the Load event of the NewPurchaseOrderItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void NewPurchaseOrderItem_Load(object sender, EventArgs e)
        {
            cmbProducts.DataSource = this.Context.Products.ToArray();
            cmbProducts.SelectedIndex = -1;
            dtExpirationDate.Value = DateTime.Now;
            if (!_New)
            {
                _ComboLoaded = true;
                cmbProducts.SelectedValue = _pItem.ProductID;
                txtVendorCode.Text = _pItem.VendorCode;
                txtQuantity.Text = _pItem.Quantity.ToString("F");
                txtUnitPrice.Text = _pItem.UnitPrice.ToString("F");
                txtTaxesPercent.Text = _pItem.TaxesPercent.ToString("F");
                txtNotes.Text = _pItem.Notes;
            }
            else _ComboLoaded = true;
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the cmbProducts control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cmbProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_ComboLoaded)
            {
                if (cmbProducts.SelectedIndex != -1)
                {
                    grpPrice.Enabled = true;
                    Product product = cmbProducts.SelectedItem as Product;
                    if (product.IsNonStockable)
                    {
                        _PurchaseUnitPrice = _SalesUnitPrice = 0;
                        txtUnitPrice.Text = "0";
                        txtQuantity.Text = "1";
                        txtQuantity.Enabled = false;
                        _NonStockable = true;
                    }
                    else
                    {
                        _PurchaseUnitPrice = product.StockableProduct.PurchaseUnitPrice;
                        _SalesUnitPrice = product.StockableProduct.SalesUnitPrice;
                        txtTaxesPercent.Text = product.StockableProduct.TaxesPercent.ToString("F");
                        txtUnitPrice.Text = _PurchaseUnitPrice.ToString("F");
                        if (product.StockableProduct.ReorderQuantity.HasValue)
                            txtQuantity.Text = product.StockableProduct.ReorderQuantity.Value.ToString("F");
                        txtQuantity.Enabled = true;
                        _NonStockable = false;
                    }

                    txtPurchasePrice.Text = _PurchaseUnitPrice.ToString("F");
                    txtSalesPrice.Text = _SalesUnitPrice.ToString("F");
                }
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the txtUnitPrice control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void txtUnitPrice_TextChanged(object sender, EventArgs e)
        {
            if (!_NonStockable)
            {
                if (!_Change)
                {
                    _Change = true;
                    double unitPrice = 0.0;
                    if (double.TryParse(txtUnitPrice.Text, out unitPrice))
                    {
                        txtDiscountPercent.Text = PurchaseOrderManager.CaluclateItemDiscount(_PurchaseUnitPrice, unitPrice).ToString("F");
                        CalculateTotalValue();
                    }
                    _Change = false;
                }
            }
            else
            {
                CalculateTotalValue();
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the txtDiscountPercent control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void txtDiscountPercent_TextChanged(object sender, EventArgs e)
        {
            if (!_NonStockable)
            {
                if (!_Change)
                {
                    _Change = true;
                    double discount = 0.0;
                    if (double.TryParse(txtDiscountPercent.Text, out discount))
                    {
                        double unitPrice = PurchaseOrderManager.CalculateItemPrice(_PurchaseUnitPrice, discount);
                        //double profit = PurchaseOrderManager.CalculateItemProfit(_PurchaseUnitPrice, unitPrice);
                        txtUnitPrice.Text = unitPrice.ToString("F");
                        CalculateTotalValue();
                    }
                    _Change = false;
                }
            }
        }

        /// <summary>
        /// Calculates the total value.
        /// </summary>
        private void CalculateTotalValue()
        {
            double quantity = 0.0, unitPrice = 0.0;
            if (double.TryParse(txtQuantity.Text, out quantity) && double.TryParse(txtUnitPrice.Text, out unitPrice))
            {
                txtValue.Text = PurchaseOrderManager.CalculateItemValue(unitPrice, quantity).ToString("F");
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the txtQuantity control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalValue();
        }

        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (superValidator1.Validate())
            {
                if (cmbProducts.SelectedIndex != -1)
                {
                    if (_New)
                    {
                        PurchaseOrderManager.CreatePurchaseItem(double.Parse(txtQuantity.Text),
                            double.Parse(txtUnitPrice.Text), cmbProducts.SelectedItem as Product,
                            double.Parse(txtDiscountPercent.Text), double.Parse(txtTaxesPercent.Text),
                            txtVendorCode.Text, txtNotes.Text, dtExpirationDate.Value, _pOrder);
                    }
                    else
                    {
                        PurchaseOrderManager.UpdatePurchaseItem(_pItem, double.Parse(txtQuantity.Text),
                            double.Parse(txtUnitPrice.Text), cmbProducts.SelectedItem as Product,
                            double.Parse(txtDiscountPercent.Text), double.Parse(txtTaxesPercent.Text),
                            txtVendorCode.Text, txtNotes.Text, dtExpirationDate.Value);
                    }
                    this.Close();
                }
                else
                {
                    MessageBox.Show(QFlow.Windows.Properties.Resources.MBChooseProduct, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (_pItem != null)
            {
                if (_pItem.IsAttached())
                {
                    this.Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, _pItem);
                }
            }
            this.Close();
        }

        /// <summary>
        /// Raises the <see cref="E:Activated"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnActivated(EventArgs e)
        {

        }
    }
}
